/*************************************************************************
 *     >      File Name: main_sub.c
 *     >    Description: This file
 *
 *     >         Author: Yang Xiaohan
 *     >           Mail: yangxiaohan_niki@163.com
 *     >   Created Time: Sun 24 Apr 2022 15:43:35 CST
 *     >   Changed Time: Sun 24 Apr 2022 15:45:35 CST
 **************************************************************************/

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
//#include "logger.h"

#define BUFSIZE 256

int get_temperature(float *temp);

#if 0
int main(int argc, char *argv[])
{
	float             temp;
	int               rv;

	rv = get_temperature(&temp);

	if(rv < 0)
	{
		printf("can not get temperature,return value :%d\n",rv);
		return -1;
	}

	printf("temperature: %f\n",temp);
}

#endif

int get_temperature(float *temp)
{
	int               fd;
	char              buf[BUFSIZE];
	char              *ptr=NULL;
	DIR               *dirp = NULL;
	struct dirent     *direntp =NULL;
	char              path[32]="/sys/bus/w1/devices/";
	char              chip_sn[32];
	int               found = 0;
	char              ds18b20_path[1024];

	dirp = opendir(path);
	if(NULL == dirp)
	{
		printf(" open folder %s failure : %s\n",path, strerror(errno));
		return -1;
	}

	while( NULL != ((direntp=readdir(dirp))) )
	{
		if(strstr (direntp->d_name,"28-"))
		{
			strncpy(chip_sn,direntp->d_name,sizeof(chip_sn));
			found = 1;
		}

	}

	closedir(dirp);

	if(!found)
	{
		printf("can not found ds18b20 chipset\n");
		return -2;
	}
	snprintf(ds18b20_path,sizeof(ds18b20_path),"%s%s/w1_slave",path,chip_sn);



	fd = open(ds18b20_path,O_RDONLY);
	if(fd < 0)
	{
		printf("open file failure: %s\n",strerror(errno));
		return -3;
	}


	memset(buf,0,sizeof(buf));

	if(read(fd,buf,sizeof(buf)) <0 )
	{
		printf("read data from fd = %d file failure : %s\n",fd,strerror(errno));
		return -4;
	}

	ptr=strstr(buf,"t=");
	if( NULL == ptr )
	{
		printf("can not find t= string\n");
		return -5;
	}

	ptr += 2;

	*temp = atof(ptr)/1000;

	close(fd);
	return 0;
}


